package com.example.auction.controller;

import com.example.auction.constant.JwtClaimsConstant;
import com.example.auction.entity.User;
import com.example.auction.entity.dto.UserDTO;
import com.example.auction.entity.dto.UserLoginDTO;
import com.example.auction.entity.vo.UserLoginVO;
import com.example.auction.entity.vo.UserVO;
import com.example.auction.properties.JwtProperties;
import com.example.auction.result.Result;
import com.example.auction.service.UserService;
import com.example.auction.utils.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Api(tags = "用户相关接口")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 微信登录
     * @param userLoginDTO
     * @return
     */
    @PostMapping("/login")
    @ApiOperation("微信登录")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO){
        log.info("微信用户登录：{}",userLoginDTO.getCode());

        //微信登录
        User user = userService.wxLogin(userLoginDTO);

        //为微信用户生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID,user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);

        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .openid(user.getOpenid())
                .token(token)
                .build();
        return Result.success(userLoginVO);
    }

    /*
    *个人信息查询
    * */
    @GetMapping("/info/{openid}")
    @ApiOperation("个人信息查询")
    public Result<UserVO> getInfoById(@PathVariable String openid){
        UserVO userVO = new UserVO();
        User user = userService.getInfoById(openid);
        BeanUtils.copyProperties(user,userVO);
        return Result.success(userVO);
    }


    @PutMapping("/info")
    @ApiOperation("修改个人信息")
    public Result<String> updateInfo(@RequestBody UserDTO userDTO){
        userService.updateInfo(userDTO);
        return Result.success("保存成功");
    }

}
